/* 消息页 */

import api from '../../utils/http.js'

Page( {
 
  data: {
    arr: [],
    userId: '',
    dialogFlag: false
  },

  onLoad(){
    this.setData({
      dialogFlag: wx.getStorageSync('token') ? true : false
    })
  },
 
  // 跳转到聊天页
  toChatPage(e) {
    let id = e.currentTarget.dataset.yourid
    let arrId = e.currentTarget.id
    let item = this.data.arr[arrId]
    wx.navigateTo({
      url: `/pages/chat/chat?yourId=${id}&yourName=${item.nickname}&yourAvatar=${item.avatar}`,
      success: () => {
        // 移除未读消息数
        wx.removeStorageSync(id + 'and' + this.data.userId + '-num')
      }
    })
  },

  // 跳转到登录方式页
  toLoginMethodPage() {
    wx.navigateTo({url: '/pages/user/codeLogin/codeLogin'})
  },

  onShow() {
    let member = wx.getStorageSync('member')
    let myName = wx.getStorageSync('userId')
    let array = []
    
    if (member !== '') {
      for (let i = 0; i < member.length; i++) {
        // 发请求拿用户头像和昵称
        wx.getStorage({
          key: 'token',
          success: res => {
            api.getUser(member[i].name).then(res => {
              let { avatar, nickname } = res.data.data
              array[i].avatar = avatar //保存头像
              array[i].nickname = nickname //保存昵称
              let time = array[i].time.split(' ')[1]
              array[i].time = time.split(':')[0] + ':' + time.split(':')[1]
              
              this.setData({ arr: array, userId: myName })
            })
          }
        })

        if (wx.getStorageSync(member[i].name + 'and' + myName) != '') {
          // 将联系人的最后一条对话记录添加到数组中
          array.push(wx.getStorageSync(member[i].name + 'and' + myName)[wx.getStorageSync(member[i].name + 'and' + myName).length - 1])

          let res = wx.getStorageSync(member[i].name + 'and' + myName + '-num')
          array[i].unread = res //保存未读消息数
        }
      }
    }
  },
})